package com.thermoberg.passport.interceptor;

import com.thermoberg.passport.util.LoginToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by hua on 2015/5/21.
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private LoginToken loginToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("request uri:" + request.getRequestURI() +
                (request.getQueryString() != null ? "?" +request.getQueryString() : ""));
        String urlString = "";
        if(request.getQueryString() != null) {
            urlString = "?" + request.getQueryString();
        }
        Cookie[] cookies = request.getCookies();
        String token = "";
        String requestType = request.getHeader("X-Requested-With");
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("logintoken".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }

        if ("".equals(token)) {
            if(requestType == null || "".equals(requestType)) {
                response.sendRedirect("/account/login?redirectUrl=" + request.getRequestURI()+urlString);
            } else {
                logger.info("is ajax request requestType: " + requestType);
                response.setStatus(401);
            }
            return false;
        }

        logger.debug("loginToken: " + token);

        try {
            String[] userInfo = loginToken.getUserInfo(token);
            if (userInfo == null) {
                logger.info("登陆token过期!");
                if(requestType == null || "".equals(requestType)) {
                    response.sendRedirect("/account/login?redirectUrl=" + request.getRequestURI()+urlString);
                } else {
                    logger.info("is ajax request requestType: " + requestType);
                    response.setStatus(401);
                }
                return false;
            } else {
                request.setAttribute("id", userInfo[0]);
                request.setAttribute("username", userInfo[1]);
                request.setAttribute("userrole", userInfo[2]);
                return true;
            }
        } catch (Exception e) {
            logger.error("解析登陆token发生错误 " + e.getMessage());
            response.sendRedirect("/account/login?redirectUrl=" + request.getRequestURI()+urlString);
            return false;
        }
    }



    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}

